﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BiliBiliCSharpStudy.old {
    /**
     * 索引器
     * 
     * === 快捷键 ===
     * indexer tab tab : 快速创建索引器
     * 
     */
    class IndexerDemo {
        public static void demo() {
            test1();
        }

        public static void test1() {
            Student7 stu = new Student7();
            stu["Math"] = 90;
            stu["Math"] = 100;
            var mathScore = stu["Math"];
            Console.WriteLine(mathScore);
        }
    }

    /**
     * === 快捷键 ===
     * indexer tab tab : 快速创建索引器
     * 
     */
    class Student7 {
        private Dictionary<string, int> scoreDict = new Dictionary<string, int>();
        public int? this[string subject] {
            get {
                if (scoreDict.ContainsKey(subject)) {
                    return this.scoreDict[subject];
                } else {
                    return null;
                }
            }
            set {
                if (value.HasValue == false) {
                    throw new Exception("Score can not be null");
                }
                if (scoreDict.ContainsKey(subject)) {
                    // 可空类型(int?)value的值是: value.Value
                    scoreDict[subject] = value.Value;
                } else {
                    // 可空类型(int?)value的值是: value.Value
                    scoreDict.Add(subject, value.Value);
                }
            }
        }
    }
}
